{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {
    "vscode": {
     "languageId": "raw"
    }
   },
   "source": [
    "---\n",
    "title: Intro to value ownership\n",
    "sidebar_position: 1\n",
    "description: Introduction to Mojo value ownership.\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A program is nothing without data, and all modern programming languages store\n",
    "data in one of two places: the call stack and the heap (also sometimes in CPU\n",
    "registers, but we won't get into that here). However, each language reads and\n",
    "writes data a bit differently—sometimes very differently. So in the following\n",
    "sections, we'll explain how Mojo manages memory in your programs and how this\n",
    "affects the way you write Mojo code.\n",
    "\n",
    ":::note\n",
    "\n",
    "For an alternate introduction to ownership in Mojo, check out our two-part blog\n",
    "post: \n",
    "[What ownership is really about: a mental model approach](https://www.modular.com/blog/what-ownership-is-really-about-a-mental-model-approach), and [Deep dive into\n",
    "ownership in Mojo](https://www.modular.com/blog/deep-dive-into-ownership-in-mojo).\n",
    "\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Stack and heap overview\n",
    "\n",
    "In general, all modern programming languages divide a running program's memory\n",
    "into four segments:\n",
    "\n",
    "- Text. The compiled program.\n",
    "- Data. Global data, either initialized or uninitialized.\n",
    "- Stack. Local data, automatically managed during the program's runtime.\n",
    "- Heap. Dynamically-allocated data, managed by the programmer.\n",
    "\n",
    "The text and data segments are statically sized, but the stack and heap change\n",
    "size as the program runs.\n",
    "\n",
    "The _stack_ stores data local to the current function. When a function is\n",
    "called, the program allocates a block of memory—a _stack frame_—that is exactly\n",
    "the size required to store the function's data, including any _fixed-size_\n",
    "local variables. When another function is called, a new stack frame is pushed\n",
    "onto the top of the stack. When a function is done, its stack frame is popped\n",
    "off the stack. \n",
    "\n",
    "Notice that we said only \"_fixed-size_ local values\" are stored in the stack.\n",
    "Dynamically-sized values that can change in size at runtime are instead\n",
    "stored in the heap, which is a much larger region of memory that allows for\n",
    "dynamic memory allocation. Technically, a local variable for such a value\n",
    "is still stored in the call stack, but its value is a fixed-size pointer to the\n",
    "real value on the heap. Consider a Mojo string: it can be any length, and \n",
    "its length can change at runtime. So the Mojo `String` struct includes some statically-sized fields, plus a pointer to a dynamically-allocated buffer\n",
    "holding the actual string data.\n",
    "\n",
    "Another important difference between the heap and the stack is that the stack is \n",
    "managed automatically—the code to push and pop stack frames is added by the\n",
    "compiler. Heap memory, on the other hand, is managed by the programmer\n",
    "explicitly allocating and deallocating memory. You may do this indirectly—by\n",
    "using standard library types like `List` and `String`—or directly, using the \n",
    "[`UnsafePointer`](/mojo/stdlib/memory/unsafe_pointer/UnsafePointer) API.\n",
    "\n",
    "Values that need to outlive the lifetime of a function (such as\n",
    "an array that's passed between functions and should not be copied) are stored\n",
    "in the heap, because heap memory is accessible from anywhere in the call stack,\n",
    "even after the function that created it is removed from the stack. This sort of\n",
    "situation—in which a heap-allocated value is used by multiple functions—is where\n",
    "most memory errors occur, and it's where memory management strategies vary the\n",
    "most between programming languages."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Memory management strategies\n",
    "\n",
    "Because memory is limited, it's important that programs remove unused data from\n",
    "the heap (\"free\" the memory) as quickly as possible. Figuring out when to free\n",
    "that memory is pretty complicated.\n",
    "\n",
    "Some programming languages try to hide the complexities of memory management\n",
    "from you by utilizing a \"garbage collector\" process that tracks all memory\n",
    "usage and deallocates unused heap memory periodically (also known as automatic\n",
    "memory management). A significant benefit of this method is that it relieves\n",
    "developers from the burden of manual memory management, generally avoiding more\n",
    "errors and making developers more productive. However, it incurs a performance\n",
    "cost because the garbage collector interrupts the program's execution, and it\n",
    "might not reclaim memory very quickly.\n",
    "\n",
    "Other languages require that you manually free data that's allocated on the\n",
    "heap. When done properly, this makes programs execute quickly, because there's\n",
    "no processing time consumed by a garbage collector. However, the challenge with\n",
    "this approach is that programmers make mistakes, especially when multiple parts\n",
    "of the program need access to the same memory—it becomes difficult to know\n",
    "which part of the program \"owns\" the data and must deallocate it. Programmers\n",
    "might accidentally deallocate data before the program is done with it (causing\n",
    "\"use-after-free\" errors), or they might deallocate it twice (\"double free\"\n",
    "errors), or they might never deallocate it (\"leaked memory\" errors). Mistakes\n",
    "like these and others can have catastrophic results for the program, and these\n",
    "bugs are often hard to track down, making it especially important that they\n",
    "don't occur in the first place.\n",
    "\n",
    "Mojo uses a third approach called \"ownership\" that relies on a collection of\n",
    "rules that programmers must follow when passing values. The rules ensure there\n",
    "is only one \"owner\" for a given value at a time. When a value's lifetime ends,\n",
    "Mojo calls its destructor, which is responsible for deallocating any heap memory\n",
    "that needs to be deallocated.\n",
    "\n",
    "In this way, Mojo helps ensure memory is freed, but it does so in a way that's\n",
    "deterministic and safe from errors such as use-after-free, double-free and\n",
    "memory leaks. Plus, it does so with a very low performance overhead.\n",
    "\n",
    "Mojo's value ownership model provides an excellent balance of programming\n",
    "productivity and strong memory safety. It only requires that you learn some new\n",
    "syntax and a few rules about how to share access to memory within your program.\n",
    "\n",
    "But before we explain the rules and syntax for Mojo's value ownership model,\n",
    "you first need to understand [value\n",
    "semantics](/mojo/manual/values/value-semantics)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Mojo",
   "language": "mojo",
   "name": "mojo-jupyter-kernel"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "mojo"
   },
   "file_extension": ".mojo",
   "mimetype": "text/x-mojo",
   "name": "mojo"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
